"""
    6E6 = 请求: 使用requests_go库tls,
    必要cookie从post_sensor中获取
    将生成的cookie传入进本地redis
"""
import json
import re


import redis
import requests_go
from curl_cffi import requests

from utils import *

Printing = True
ONLINE_PROXY = False
GET_API = False
UP_COOKIE = False
RETRUN_ABCK = True
Worker = 15

success_count = 1

# 131-136及以上可用  edge134以上
start = 124
end = 139
all_UA_chrome = [
    [f'\"Google Chrome\";v=\"{i}\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"{i}\"' for i in range(start, end)],
    [f'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{j}.0.0.0 Safari/537.36'
     for j in range(start, end)]
]
all_UA_edge = [
    [f"\"Chromium\";v=\"{i}\", \"Not:A-Brand\";v=\"24\", \"Microsoft Edge\";v=\"{i}\"" for i in range(start, end)],
    [
        f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{j}.0.0.0 Safari/537.36 Edg/{j}.0.0.0"
        for j in range(start, end)]
]
all_UA = [
    all_UA_edge[0] + all_UA_chrome[0],
    all_UA_edge[1] + all_UA_chrome[1]
]


class Akamai:
    def __init__(self, init_url, rds=None):
        self.proxy = {
            "http": "https://127.0.0.1:7890",
            "https": "https://127.0.0.1:7890",
        }
        self.cookies = {}
        self.init_url = init_url
        self.akm_url = "None"
        self.ua_index = 0
        self.timeout = 5
        self.tls_config = ""
        self.rds = rds

    # 请求首页获取初始的abck
    def get_init_url(self):
        headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "priority": "u=0, i",
            "sec-ch-ua": all_UA[0][self.ua_index],
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "cross-site",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent": all_UA[1][self.ua_index]
        }
        for i in range(3):
            try:
                resp = requests.get(self.init_url, headers=headers, proxies=self.proxy, timeout=self.timeout)
                self.akm_url = "https://www.goindigo.in" + re.findall('src="([^"]+)"', resp.text)[-1]
                self.cookies.update(resp.cookies.get_dict())
                return True
            except Exception as e:
                self.proxy = get_abroad_proxy()
                if i >= 2:
                    print("请求首页失败", e)
                    return False

    # 获取JS文件
    def get_js(self):
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "priority": "u=1",
            "referer": "https://www.goindigo.in/book/flight-select.html",
            "sec-ch-ua": all_UA[0][self.ua_index],
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "script",
            "sec-fetch-mode": "no-cors",
            "sec-fetch-site": "same-origin",
            "user-agent": all_UA[1][self.ua_index]
        }
        for i in range(3):
            try:
                resp = requests.get(self.akm_url, headers=headers, proxies=self.proxy, timeout=self.timeout,
                                    cookies=self.cookies)
                self.cookies.update(resp.cookies.get_dict())
                # 使用re替换一下js文件中的内容
                pattern = r'\[(\w+),\s*(\w+)\];'
                replacement = r'new CustomArray(\1, \2);'
                return re.sub(pattern, replacement, resp.text)
            except Exception as e:
                self.proxy = get_abroad_proxy()
                if i >= 2:
                    print("获取JS文件失败", e)
                    return False

    # 获取sensor
    def get_sensor(self, js_data):
        data = {"bm_sz": self.cookies.get("bm_sz"), "js": js_data, "UA": all_UA[1][self.ua_index]}
        resp = requests.post("http://127.0.0.1:5889/getSensor", json=data)
        return resp.text

    def post_sensor(self, sensor_data):
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "text/plain;charset=UTF-8",
            "csrf-token": "undefined",
            "origin": "https://www.goindigo.in",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://www.goindigo.in/",
            "sec-ch-ua": all_UA[0][self.ua_index],
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": all_UA[1][self.ua_index]
        }
        for i in range(3):
            # self.tls_config = get_tls_config(self.akm_url, headers=headers, TYPE="POST", ja3=random.choice(ja3_list))
            self.tls_config = requests_go.tls_config.TLS_EDGE_131_LATEST
            try:
                resp = requests_go.post(self.akm_url, headers=headers, proxies=self.proxy, cookies=self.cookies,
                                        data=sensor_data, timeout=self.timeout,
                                        tls_config=self.tls_config)
                self.cookies.update(resp.cookies.get_dict())
                # print(resp.text, len(self.cookies.get("_abck")))
                return True
            except Exception as e:
                self.proxy = get_abroad_proxy()
                if i >= 2:
                    print("提交sensor_data失败", e)
                    # print(self.tls_config)
                    return False

    def get_api(self):
        url = "https://api-prod-flight-skyplus6e.goindigo.in/v1/flight/search"
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJpYmUiLCJqdGkiOiJhNTdmODBkNi0yOTQ1LWE2NzUtMTJjNC1kY2M4ODcxOTQxNDIiLCJpc3MiOiJkb3RSRVogQVBJIn0.F6PqzAMr_8X5GXj4gj0PftRydEoTv6V4X3CEsJWk83E",
            "cache-control": "no-cache",
            "content-type": "application/json",
            "origin": "https://www.goindigo.in",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://www.goindigo.in/",
            "sec-ch-ua": all_UA[0][self.ua_index],
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "traceparent": "00-0000000000000000c5a4e79febf21b23-2cca75cd70ce9bca-01",
            "user-agent": all_UA[1][self.ua_index],
            "user_key": "31e90be8fff2f5e2eea242c225f21b1a",
            "x-datadog-origin": "rum",
            "x-datadog-parent-id": "3227521608185715658",
            "x-datadog-sampling-priority": "1",
            "x-datadog-trace-id": "14241762595696679715"
        }
        data = {
            "codes": {
                "currency": "INR",
                "promotionCode": ""
            },
            "criteria": [
                {
                    "dates": {
                        "beginDate": "2025-06-28"
                    },
                    "flightFilters": {
                        "type": "All"
                    },
                    "stations": {
                        "originStationCodes": [
                            "AJL"
                        ],
                        "destinationStationCodes": [
                            "ALA"
                        ]
                    }
                }
            ],
            "passengers": {
                "residentCountry": "IN",
                "types": [
                    {
                        "count": 1,
                        "discountCode": "",
                        "type": "ADT"
                    }
                ]
            },
            "taxesAndFees": "TaxesAndFees",
            "tripCriteria": "oneWay",
            "isRedeemTransaction": False
        }
        data = json.dumps(data, separators=(',', ':'))
        for i in range(3):
            tls_list = [requests_go.tls_config.TLS_EDGE_131_LATEST, requests_go.tls_config.TLS_CHROME_131_LATEST,
                        requests_go.tls_config.TLS_CHROME_130, requests_go.tls_config.TLS_CHROME_111_129_SAFE,
                        requests_go.tls_config.TLS_CHROME_130_SAFE, requests_go.tls_config.TLS_CHROME_111_129,
                        requests_go.tls_config.TLS_CHROME_122, requests_go.tls_config.TLS_CHROME_110,
                        requests_go.tls_config.TLS_CHROME_103, requests_go.tls_config.TLS_CHROME_101
                        ]
            try:
                resp = requests_go.post(url, headers=headers, proxies=self.proxy, cookies=self.cookies, data=data,
                                        tls_config=requests_go.tls_config.TLS_CHROME_101)
                # tls_config=self.tls_config)
                global success_count
                if resp.status_code == 403:
                    print("403请求失败 " + "-" * 100)
                    return False
                print(f"第{success_count}次请求成功" + str(len(self.cookies.get("_abck"))) + "+" * 100)
                print(resp.text[:200])
                success_count += 1
                return True
            except Exception as e:
                self.proxy = get_abroad_proxy()
                if i >= 2:
                    print("请求失败" + str(len(self.cookies.get("_abck"))) + "-" * 100)
                    print(e)

    def upload_abck(self):
        if self.cookies.get("_abck"):
            cookie = json.dumps(self.cookies)
            self.rds.lpush("6E", cookie, cookie, cookie)
            print("up cookie success")
            return True
        return False

    def start(self):
        for i in range(10):
            try:
                if ONLINE_PROXY:
                    self.proxy = get_abroad_proxy()
                self.ua_index = random.randint(0, len(all_UA[0]) - 1)
                get_index_success = self.get_init_url()
                if not get_index_success:
                    continue
                js_data = self.get_js()
                if not js_data:
                    continue
                # 调用本地接口获取sensor
                sensor_data = self.get_sensor(js_data)
                if sensor_data.find("error") != -1:
                    print("Error 执行接口", sensor_data)
                    continue
                # 提交sensor_data
                post_sensor = self.post_sensor(sensor_data)
                if not post_sensor:
                    continue
                if len(self.cookies.get("_abck")) >= 580:
                    if GET_API:
                        self.get_api()
                    elif UP_COOKIE:
                        self.upload_abck()
                    elif RETRUN_ABCK:
                        return self.cookies
            except Exception as e:
                print("主流程出错", e)
                return False

            # finally:
            #     self.cookies.clear()


if __name__ == '__main__':
    init_url = "https://www.goindigo.in/flights?linkNav=Flight%7CBook%7CBook"
    rds = redis.Redis(host="127.0.0.1", port=6379, password='test6e', decode_responses=True)
    akamai = Akamai(init_url, rds)
    result = akamai.start()
    print(result)
